<template>
  <el-dialog append-to-body :close-on-click-modal="false" :title="option.modalTitle" :visible.sync="visibile" width="60%" top="5vh" @open="open" @close="hideModal">
    <!-- 副标题 -->
    <div class="common-modal-sub-title" v-if="option.subTitle && option.subTitle.show">
      <i :class="[option.subTitle.icon || 'el-icon-vertical-bar', 'avue-group__icon', 'mr10']"></i>
      <h1 class="avue-group__title">{{ option.subTitle.name }}</h1>
    </div>
    <avue-crud
      ref="crud"
      :table-loading="loading"
      :data="data"
      :option="tableOption"
      :row-class-name="tableRowClassName"
      @search-change="searchChange"
      @search-reset="searchReset"
      :page.sync="page"
      @on-load="onLoad"
      @selection-change="selectionChange"
      @row-click="rowClick"
      @row-dblclick="rowDbclick"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @tree-load="treeLoad"
    ></avue-crud>
    <div slot="footer" class="dialog-footer" v-if="option.rowSelectionType != 'single'">
      <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="submitForm">保存</el-button>
      <el-button size="small" icon="el-icon-circle-close" @click="hideModal">取消</el-button>
    </div>
    <div slot="footer" class="dialog-footer close" v-if="option.showDetails">
      <el-button size="small" icon="el-icon-circle-close" @click="hideModal">关 闭</el-button>
    </div>
  </el-dialog>
</template>
<script>
import request from '@/router/axios';
import { templateConfig } from './template.js';
import { getPageAreaWithAttr } from '@/api/system/extendPage';
export default {
  name: 'global-modal-template',
  props: {
    option: {
      type: Object,
      default: () => ({})
    },
    visibile: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    visibile: {
      handler(val) {
        console.log('val', val);
        // this.visibile = val;
        // this.$emit('update:visibile', val);
        if (!val) {
          this.$emit('newKey', '');
        }
      }
    }
  },
  data() {
    return {
      query: {}, // 外界传来的参数集合
      method: 'get',
      tableOption: {
        height: 'calc(100vh - 480px)',
        calcHeight: 30,
        border: true, //表格外框线是否显示
        stripe: true, //表格是否显示条纹
        header: true, //表格头部是否显示
        index: true, //表格数据序号
        page: false, //表格分页是否显示
        addBtn: false, //新增按钮是否显示
        menu: false, //表格操作栏是否显示
        refreshBtn: true, //刷新按钮是否显示
        columnBtn: false, //控制表格列是否显示按钮是否显示
        // searchBtn: false
        searchMenuSpan: 6, //搜索按钮所占宽度
        searchMenuPosition: 'right', //搜索按钮位置
        column: [], //表格列配置
        selection: false, //表格是否多选
        reserveSelection: false, //表格是否分页多选
        searchShow: true,
        isFilter: false, //是否对数据进行过滤
        query: {},
        subTitle: {
          // 表格顶部展示子标题
          show: false,
          icon: '',
          name: ''
        },
        filterOption: {
          //表格数据过滤
          isFilter: false,
          prop: '',
          data: [] //过滤的数据
        }
      }, //表格属性
      // 分页器配置
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      }, //表格分页
      selectedRows: [], //表格选中行数据
      data: [], //表格数据
      loading: false,
      titleInfo: '',
      filterOption: {}
    };
  },
  methods: {
    open() {
      let { templateName } = this.option;
      if (templateConfig[templateName] && !this.option.columnDefs) {
        this.option.columnDefs = templateConfig[templateName];
      }
      this.tableOption.column = this._cloneDeep(this.option.columnDefs);
      console.log(this.tableOption);
      this.titleInfo = this.option.titleInfo;
      this.tableOption.page = this.option.isPage;
      // 浅拷贝crud配置项  this.tableOption
      this._assgin(this.tableOption, this.option);
      this.filterOption = this.tableOption.filterOption;
      this.method = this.tableOption.method;
      // 关闭分页功能时将pageSize=10000;
      if (!this.tableOption.page) {
        this.page.total = 0;
        this.page.pageSize = 10000;
      }
      this._forEach(this.tableOption.columnDefs, (item) => {
        if (item.searchValue) {
          this.query[item.prop] = item.searchValue;
        }
      });
      // 外界接口参数
      // this.query = this.tableOption.query;
      if (this.option.rowSelectionType === 'single') {
        this.tableOption.selection = false;
      } else {
        this.tableOption.selection = true;
        this.tableOption.reserveSelection = true;
      }
      // this.getExtendField();
    },
    /**
     * 首次加载表格
     */
    onLoad(page, params = {}) {
      this.createRowData(page, Object.assign(params, this.query, this.tableOption.query));
    },

    /**
     * 多选事件
     */
    selectionChange(list) {
      this.selectedRows = list;
    },

    /**
     * 单击事件
     */
    rowClick(row) {
      if (this.tableOption.selection && !this.tableOption.isToggleSelection) {
        this.$refs.crud.toggleRowSelection(row);
      }
    },

    /**
     * 双击事件
     */
    rowDbclick(row) {
      if (!this.option.readonly && this.option.rowSelectionType === 'single') {
        this.$emit('update:visibile', false);
        this.$emit('getSelectedRows', row, this.titleInfo);
      }
    },
    /**
     * 改变当前页
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 改变当前页大小
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },

    /**
     * 隐藏模态框
     */
    hideModal() {
      this.$emit('update:visibile', false);
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    /**
     * 刷新
     */
    refreshChange() {
      this.onLoad(this.page);
    },
    /**
     * 搜索重置
     */
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    /**
     * 查询表格数据
     */
    createRowData(page, params) {
      let that = this;
      that.loading = true;
      //是否默认加载数据
      request({
        url: that.option.url,
        method: that.method || 'get',
        params: {
          current: page.currentPage,
          size: page.pageSize,
          ...params
        }
      }).then((res) => {
        const data = res.data.data;
        console.log(that.option);
        if (data.records) {
          that.data = data.records;
          if (that.option.lazy && that.option.hasChildren) {
            that.data = data.records.map((item) => {
              return {
                ...item,
                hasChildren: item[that.option.hasChildren]
              };
            });
          }
        } else {
          that.data = data;
        }

        if (that.filterOption.isFilter) {
          //过滤选中的数据
          that.data = that._differenceWith(that.data, that.filterOption.data, (item1, item2) => {
            return item1[that.filterOption.prop] === item2;
          });
        }
        if (data.size) {
          that.page.total = data.total;
          that.page.pageSize = data.size;
        }
      });
      setTimeout(() => {
        this.loading = false;
      }, 300);
    },

    tableRowClassName({ row, rowIndex }) {
      if (this.option.isToggleSelection && this.option.selectionArray && this.option.selectionArray.length) {
        return this.option.selectionArray.includes(row[this.option.filterKey]) ? 'disabled-row' : '';
      } else {
        return '';
      }
    },
    /**
     * 提交选择行
     */
    submitForm() {
      if (this.option.isSingleChoice && this.selectedRows.length > 1) {
        this.$message({
          type: 'warning',
          message: '当前功能只能选中一条数据！'
        });
        return;
      }
      this.$emit('getSelectedRows', this.selectedRows, this.titleInfo);
      this.$emit('update:visibile', false);
    },
    getExtendField() {
      getPageAreaWithAttr({ parentAreaCode: this.$route.fullPath }).then((res) => {
        this.customAttributeList = this._get(res, 'data.data', []);
        let searchOption = this._find(this.customAttributeList, { type: 'SEARCH' });
        let searchOptionName = searchOption && searchOption.code.includes('-') ? searchOption.code.split('-')[0] : '';
        this._forEach(this.customAttributeList, (item) => {
          this._forEach(item.pageAttributeVOList, (attrItem) => {
            if (item.code === this.titleInfo) {
              this.tableOption.column.push({
                label: attrItem.lableCnName,
                prop: attrItem.attributeKey,
                type: attrItem.controlType,
                disabled: attrItem.isAllowEdit,
                value: attrItem.defaultValue,
                span: attrItem.pageAreaType === 'DIALOG' ? 12 : 6
              });
            }
          });
        });
        if (searchOptionName) {
          this._forEach(searchOption.pageAttributeVOList, (item) => {
            let columnIndex = this._findIndex(this.tableOption.column, { prop: item.attributeKey });
            this.tableOption.column[columnIndex]['search'] = true;
          });
        }
      });
    },
    treeLoad(tree, treeNode, resolve) {
      const that = this;
      if (that.tableOption.lazy && that.tableOption.lazyTreeUrl) {
        const parentId = tree.id;
        request({
          url: that.tableOption.lazyTreeUrl,
          method: 'get',
          params: {
            parentId
          }
        }).then((res) => {
          let data = res.data.data;
          if (that.option.hasChildren) {
            data = data.map((item) => {
              return {
                ...item,
                hasChildren: item[that.option.hasChildren]
              };
            });
          }
          resolve(data);
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.el-form-item--small.el-form-item {
  margin-bottom: 0;
}
.common-modal-sub-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  margin: -10px 0;
}
</style>

<style lang="scss">
.disabled-row {
  background: #caf982 !important;
  td {
    background: #caf982 !important;
  }
  .el-checkbox {
    cursor: not-allowed;
  }
}
</style>
